/**
 *  created by jsq on 2017/11/10
 *  2018/12/20优化代码
 */
import React from 'react';
import {connect} from 'react-redux';
import {messages} from "share/common";
import companyGroupService from 'containers/setting/company-group/company-group.service';
import menuRoute from 'routes/menuRoute';
import config from 'config';
import {Form, Button, Select, Popover, Icon, Popconfirm, Table, message} from 'antd';
import ListSelector from 'components/list-selector';
import BasicInfo from 'components/basic-info';
import 'styles/setting/company-group/company-group-detail.scss';
import ResizeTable from "components/resize-table";

class CompanyGroupDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      buttonLoading: false,
      batchCompany: true,
      companyListSelector: false,  //控制公司选则弹框
      companyGroup: {},
      data: [],
      edit: false,
      lov: {
        type: "company",
        visible: false,
        listSelectedData: {}
      },
      selectedRowKeys: [],
      selectedEntityOIDs: [],   //已选择的列表项的OIDs
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
      },
      infoList: [
        {
          type: 'input', id: 'companyGroupCode', isRequired: true,
          disabled: true, label: messages('setting.key244'/*公司组代码*/) + " :"
        },
        {
          type: 'input', id: 'companyGroupName',
          isRequired: false, label: messages('setting.key245'/*公司组名称*/) + " :"
        },
        {
          type: 'select', id: 'setOfBooksId',
          label: messages('setting.key246'/*账套*/) + " :", options: [],
          getUrl: `${config.baseUrl}/api/setOfBooks/by/tenant`,
          method: 'get', labelKey: 'setOfBooksName', valueKey: 'id', getParams: {roleType: 'TENANT'}
        },
        {
          type: 'switch', id: 'enabled',
          label: messages('common.column.status') + " :"/*状态*/
        },
      ],
      columns: [
        {
          title: messages('setting.key247'/*公司代码*/),
          key: 'companyCode', dataIndex: 'companyCode'
        },
        {
          title: messages('setting.key248'/*公司名称*/),
          key: 'companyName', dataIndex: 'companyName', /*公司明称*/
          render: record => (
            <span>{record ? <Popover content={record}>{record} </Popover> : '-'} </span>)
        },

        {
          title: messages('common.operation'),
          key: 'operation', width: '15%', render: (text, record) => (
          <span>
            <Popconfirm onConfirm={(e) => this.deleteItem(e, record)}
                        title={messages('setting.key1446', {controlRule: record.controlRuleName}/*你确认要删除？*/)}>
              <a href="#" onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
              }}>{messages('common.delete')}</a>
            </Popconfirm>
          </span>)
        },  //操作
      ],
      selectorItem: {
        title: messages('setting.key250'/*选择公司*/),
        url: `${config.baseUrl}/api/company/by/condition`,
        searchForm: [
          {
            type: 'input',
            id: 'companyCode',
            label: messages('setting.key251'/*公司代码*/)
          },
          {
            type: 'input', id: 'name',
            label: messages('setting.key252'/*公司名称*/)
          },
          {
            type: 'input', id: 'companyCodeFrom',
            label: messages('setting.key253'/*公司代码从*/)
          },
          {
            type: 'input', id: 'companyCodeTo',
            label: messages('setting.key254'/*公司代码至*/)
          }
        ],
        columns: [
          {
            title: messages('setting.key251'/*公司代码*/),
            dataIndex: 'companyCode'
          },
          {
            title: messages('setting.key252'/*公司名称*/),
            dataIndex: 'name'
          },

        ],
        key: 'companyOID'
      }
    }
  }

  componentWillMount() {
    //根据路径上的id,查出该条完整数据
    companyGroupService.getCompanyGroupById(this.props.params.id).then((response) => {
      if (response.status === 200) {
        response.data.setOfBooksId = {
          label: response.data.setOfBooksName,
          value: response.data.setOfBooksId
        }
      }
      this.setState(
        {
          companyGroup: response.data
        },
        this.getList)
    });
  }

  deleteItem = (e, record) => {
    this.setState({loading: true});
    let param = [];
    typeof record === 'undefined' ? param = this.state.selectedEntityOIDs : param.push(record.id);
    companyGroupService.deleteCompany(param).then(response => {
      // name删除成功
      message.success(messages('common.delete.success', {name: typeof record === 'undefined' ? "" : record.companyName}));
      this.setState({
        selectedRowKeys: [],
        selectedEntityOIDs: []
      }, this.getList);
    }).catch((e) => {
      if (e.response) {
        message.error(`${messages('common.operate.filed')},${e.response.data.message}`)
      }
    })
  };

  //保存所做的详情修改
  handleUpdate = (value) => {
    value.id = this.props.params.id;
    companyGroupService.updateCompanyGroup(value).then((response) => {
      if (response) {
        message.success(messages('setting.key256'/*保存成功！*/));
        response.data.setOfBooksId = {label: response.data.setOfBooksName, value: response.data.setOfBooksId};
        this.setState({
          companyGroup: response.data,
          edit: true
        })
      }
    })
  };

  //查询公司组子公司
  getList() {
    let params = {
      companyGroupId: this.props.params.id,
      size: this.state.pagination.pageSize,
      page: this.state.pagination.page
    };
    companyGroupService.getCompanies(params).then(response => {
      response.data.map((item) => {
        item.key = item.id
      });
      let pagination = this.state.pagination;
      pagination.total = Number(response.headers['x-total-count']);
      if (response.status === 200) {
        this.setState({
          pagination,
          loading: false,
          data: response.data
        })
      }
    })
  }


  //控制是否编辑
  handleEdit = (flag) => {
    this.setState({edit: flag})
  };

  //控制是否弹出公司列表
  showListSelector = (flag) => {
    let lov = this.state.lov;
    lov.visible = flag;
    this.setState({
      lov
    })
  };


  handleBack = () => {
    this.context.router.push(menuRoute.getMenuItemByAttr('company-group', 'key').url);
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    this.setState({selectedRowKeys});
  };

  //选择一行
  //选择逻辑：每一项设置selected属性，如果为true则为选中
  //同时维护selectedEntityOIDs列表，记录已选择的OID，并每次分页、选择的时候根据该列表来刷新选择项
  onSelectRow = (record, selected) => {
    let temp = this.state.selectedEntityOIDs;
    if (selected)
      temp.push(record.id);
    else
      temp.delete(record.id);
    this.setState({
      selectedEntityOIDs: temp,
      batchCompany: temp.length > 0 ? false : true
    })
  };

  //全选
  onSelectAllRow = (selected) => {
    let temp = this.state.selectedEntityOIDs;
    if (selected) {
      this.state.data.map(item => {
        temp.addIfNotExist(item.id)
      })
    } else {
      this.state.data.map(item => {
        temp.delete(item.id)
      })
    }
    this.setState({
      selectedEntityOIDs: temp,
      batchCompany: temp.length > 0 ? false : true
    })
  };

  //换页后根据OIDs刷新选择框
  refreshRowSelection() {
    let selectedRowKeys = [];
    this.state.selectedEntityOIDs.map(selectedEntityOID => {
      this.state.data.map((item, index) => {
        if (item.id === selectedEntityOID)
          selectedRowKeys.push(index);
      })
    });
    this.setState({selectedRowKeys});
  }

  //清空选择框
  clearRowSelection() {
    this.setState({selectedEntityOIDs: [], selectedRowKeys: []});
  }

  //处理公司弹框点击ok,添加公司
  handleListOk = (result) => {
    let lov = this.state.lov;
    let param = [];
    result.result.map((item) => {
      param.push({companyGroupId: this.props.params.id, companyId: item.id})
    });
    companyGroupService.addCompanies(param).then((response) => {
      if (response.status === 200) {
        lov.visible = false;
        this.setState({
          loading: true,
          lov
        }, this.getList)
      }
    });
  };

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        current: pagination.current,
        page: pagination.current - 1,
        pageSize: pagination.pageSize,
        total: pagination.total
      }
    }, () => {
      this.getList();
    })
  };

  goToNewCompanyGroup = () => {
    let url = menuRoute.getRouteItem('new-company-group').url.replace(':companyGroupId', this.props.params.id);
    this.context.router.push(url)
  }

  render() {
    const {
      edit, lov, pagination, companyGroup, columns, data, infoList,
      selectedRowKeys, batchCompany, selectorItem
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      onSelect: this.onSelectRow,
      onSelectAll: this.onSelectAllRow
    };
    let extraParamsList = {};
    if (JSON.stringify(companyGroup) != "{}") {
      extraParamsList = {"companyGroupId": companyGroup.id, "setOfBooksId": companyGroup.setOfBooksId.value}
    }
    return (
      <div className="budget-item-detail">
        <BasicInfo
          infoList={infoList}
          infoData={companyGroup}
          updateHandle={this.handleUpdate}
          updateState={edit}
          handleEdit={this.goToNewCompanyGroup}/>
        <div className="table-header">
          <div className="table-header-title">
            {/*共搜索到*条数据*/}
            {messages('common.total', {total: `${pagination.total}`})}
          </div>
          <div className="table-header-buttons">
            <Button type="primary" onClick={() => this.showListSelector(true)}>
              {messages('common.add')}
            </Button>
            <Button disabled={batchCompany} onClick={this.deleteItem}>
              {messages('common.delete')}
            </Button>
          </div>
        </div>
        <ResizeTable
          dataSource={data}
          columns={columns}
          rowSelection={rowSelection}
          pagination={pagination}
          onChange={this.onChangePager}
          size="middle"
          bordered
        />
        <a style={{fontSize: '14px', paddingBottom: '20px'}}
           onClick={this.handleBack}>
          <Icon type="rollback" style={{marginRight: '5px'}}/>{messages('common.back')}</a>
        <ListSelector
          visible={lov.visible}
          selectorItem={selectorItem}
          onCancel={() => this.showListSelector(false)}
          onOk={this.handleListOk}
          extraParams={extraParamsList}/>
      </div>)
  }
}

CompanyGroupDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

const WrappedCompanyGroupDetail = Form.create()(CompanyGroupDetail);

export default connect(mapStateToProps)(WrappedCompanyGroupDetail);

